package com.hs.authcenter.config;

import com.hs.authcenter.enhancer.JwtTokenEnhancer;
import com.hs.authcenter.service.HushangUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author 胡尚
 * @Date: 2024/7/26 9:10
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    /**
     * 我们自定义的查询用户信息的service类
     */
    @Autowired
    private HushangUserDetailsService hushangUserDetailsService;

    /**
     * 在SpringSecurity配置文件中，往Spring容器中添加了一个AuthenticationManager类型的bean
     */
    @Autowired
    private AuthenticationManager authenticationManagerBean;

    /**
     * 指定token存储策略是jwt
     */
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 对jwt生成的token增强，添加等多的用户信息至token中
     */
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * 认证服务器的安全配置
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 第三方客户端校验token需要带入 clientId 和clientSecret来校验
        security.checkTokenAccess("isAuthenticated()")
                // 来获取我们的tokenKey需要带入clientId,clientSecret
                .tokenKeyAccess("isAuthenticated()");

        //允许表单认证
        security.allowFormAuthenticationForClients();
    }

    /**
     * 配置客户端属性
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 配置授权服务器存储第三方客户端的信息  基于DB存储   oauth_client_details
        clients.withClientDetails(clientDetails());

    }

    @Bean
    public ClientDetailsService clientDetails(){
        // JdbcClientDetailsService就会去操作oauth_client_details数据表
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 配置授权服务器端点的非安全特性:如token store、token
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        //配置JWT的内容增强器
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManagerBean)
                // refresh_token是否重复使用
                .reuseRefreshTokens(false)
                // 刷新令牌授权包含对用户信息的检查
                .userDetailsService(hushangUserDetailsService)
                // 支持GET,POST请求
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST)
                //指定token存储策略是jwt
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                // jwt token增强，添加更多的 用户信息至token中
                .tokenEnhancer(enhancerChain);
    }
}
